<template>
  <div>
    <!--  CMS-SAP资金余额对账表 -->
    <TopFilter :list="topFilterList" :cols="3" @filterChange="changeHandle" @resetChange="resetChange" @onCollapse="collapseHandle" :labelWidth="110"></TopFilter>

    <Spin :spinning="exportLoading" tip="Loading...">
      <FilterTable
        ref="table"
        columnsRef="qjhcms-sapFundBalanceStatement"
        :isSelectColumn="false"
        :columns="columns"
        :fetchapi="fetchApi"
        :params="fetchParams"
        :datakey="'records'"
        :cellstyles="cellstyles"
        :onSyncTableData="syncTableData"
        :onColumnsChange="columns => (this.columns = columns)"
      >
        <template slot="controls" slot-scope="props">
          <multiuse-button size="small" type="primary" :click="sendHandle">生成对账</multiuse-button>
          <multiuse-button size="small" type="primary" :click="exportHandle">导 出</multiuse-button>
        </template>
      </FilterTable>
    </Spin>

    <!-- 经销商查询 -->
    <BaseDialog :visible.sync="isDealer" title="经销商查询" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">
      <OwnerSearch :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>
  </div>
</template>
<script>
import moment from 'moment';
import { dictionary } from '@/utils/dictMixin';
import { exportExcelFile } from '@/utils/index';
import { queryList, saveData, exportExcel,exporturl } from '@/api/omFinance/MoneyManage/cms-sapFundBalanceStatement';
import OwnerSearch from '../ownerSeacher';
import { isArcfox } from '@/api/cms-api/origin/commonDealerType';

export default {
  name: 'cms-sapFundBalanceStatement',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {
        powerType: 60081001,
        verifyYear: moment().format('YYYY'),
        verifyMonth: moment().format('MM')
      },
      formData: {},
      cellstyles: [],
      isDealer: false,
      visible: false,
      exportLoading: false
    };
  },
  components: {
    OwnerSearch
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    if (isArcfox()) {
      this.topFilterList.find(x => x.fieldName == 'powerType').initialValue = 60081002;
      this.topFilterList.find(x => x.fieldName == 'powerType').itemList = [{ text: '新能源', value: 60081002 }];
    } else {
      this.topFilterList.find(x => x.fieldName == 'powerType').initialValue = 60081001;
      this.topFilterList.find(x => x.fieldName == 'powerType').itemList = this.createDictList('6008');
    }
  },
  methods: {
    syncTableData(data) {
      if (!data.length) return;
      data.forEach(x => {
        if (x.vehicleAccountDifferences != 0) {
          this.cellstyles.push({ row: x, dataIndex: 'vehicleAccountDifferences', styles: { backgroundColor: 'red' } });
        }
        if (x.partAccountDifferences != 0) {
          this.cellstyles.push({ row: x, dataIndex: 'partAccountDifferences', styles: { backgroundColor: 'red' } });
        }
        if (x.vehicleRebateDifferences != 0) {
          this.cellstyles.push({ row: x, dataIndex: 'vehicleRebateDifferences', styles: { backgroundColor: 'red' } });
        }
        if (x.depositDifferences != 0) {
          this.cellstyles.push({ row: x, dataIndex: 'depositDifferences', styles: { backgroundColor: 'red' } });
        }
      });
    },
    changeHandle(params) {
      params.verifyYear = params.verifyYearAndMonth.split('-')[0];
      params.verifyMonth = params.verifyYearAndMonth.split('-')[1];
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      params.powerType = isArcfox() ? 60081002 : 60081001;
      params.verifyYear = params.verifyYearAndMonth.split('-')[0];
      params.verifyMonth = params.verifyYearAndMonth.split('-')[1];
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler1(val, type) {
      this.isAdd = val;
      if (type == 'refresh') {
        this.fetchParams = Object.assign({}, this.fetchParams);
      }
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      this.visible = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCodes').initialValue = dealerCodes.toString();
      }
    },
    addHandle() {
      this.isAdd = true;
    },
    detailHandle() {
      this.visible = true;
    },
    // 生成
    async sendHandle() {
      await this.$confirm('是否生成对账单（拉取SAP数据）？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          let powerType = this.topFilterList.find(x => x.fieldName == 'powerType').initialValue;
          let res = await saveData({ powerType: powerType });
          if (res.resultCode == 200) {
            this.$notify.success({
              title: '提示信息',
              message: '操作成功'
            });
            this.fetchParams = Object.assign({}, this.fetchParams);
          }
        })
        .catch(() => {});
    },
    // 导出
    async exportHandle() {
      let json = Object.assign({}, { CODE: 'CODE_0000085' }, this.fetchParams);
      let res = await exporturl(json);
      if (res.resultCode == 200) {
        this.$router.push('/admin/auth/oem/downloadCenter');
      }
      // await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
      //   confirmButtonText: '下载',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      //   .then(() => {
      //     this.exportLoading = true;

      //     exportExcel(this.fetchParams)
      //       .then(response => {
      //         exportExcelFile(response.data, 'CMS-SAP资金余额对账表');
      //         this.exportLoading = false;
      //       })
      //       .catch(err => {
      //         console.log(err);
      //       });
      //   })
      //   .catch(() => {
      //     this.$message({
      //       type: 'info',
      //       message: '已取消'
      //     });
      //   });
    },
    createdFrom() {
      return [
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCodes',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'DATE',
          label: '对账月份',
          fieldName: 'verifyYearAndMonth',
          initialValue: moment().format('YYYY-MM'),
          dateType: 'month',
          clearable: false
        },
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '请选择',
          initialValue: '',
          itemList: [],
          clearable: false
        },
        {
          type: 'RANGE_DATE',
          label: '对账拉取日期',
          fieldName: 'createdStartDate|createdEndDate',
          initialValue: [],
          dateType: 'exactdaterange'
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // {
        //   title: '操作',
        //   dataIndex: 'column-action',
        //   width: 50,
        //   fixed: 'left',
        //   render: (props, h) => {
        //     return (
        //       <div>
        //         <multiuse-button size="mini" type="text" onClick={() => this.detailHandle(props.row)}>
        //           明细
        //         </multiuse-button>
        //       </div>
        //     );
        //   }
        // },

        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '对账月份',
          dataIndex: 'verifyYeahMonth',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '动力形式',
          dataIndex: 'powerType',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('6008'),
          render: props => {
            return <span>{this.createDictText(props.row.powerType, '6008')}</span>;
          }
        },
        {
          title: 'CMS账户总余额',
          dataIndex: 'cmsAccountAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'CMS整车款余额',
          dataIndex: 'vehicleAccountAdjustment',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'CMS配件款余额',
          dataIndex: 'partAccountAdjustment',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'CMS返利余额',
          dataIndex: 'vehicleRebateAdjustment',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'CMS建店保证金余额',
          dataIndex: 'depositAdjustment',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'SAP整车款余额',
          dataIndex: 'vehicleAccountAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'SAP配件款余额',
          dataIndex: 'partAccountAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'SAP返利余额',
          dataIndex: 'vehicleRebateAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: 'SAP建店保证金余额',
          dataIndex: 'depositAmount',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '整车款差异',
          dataIndex: 'vehicleAccountDifferences',
          sorter: true,
          filter: true,
          filterType: 'input'
        },

        {
          title: '配件款差异',
          dataIndex: 'partAccountDifferences',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利差异',
          dataIndex: 'vehicleRebateDifferences',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '建店保证金差异',
          dataIndex: 'depositDifferences',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '对账拉取日期',
          dataIndex: 'createdAt',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'yyyy-MM-dd'
        }
      ];
    }
  }
};
</script>
